package cn.net.yugu.doraemon.api.common.response;

import cn.net.yugu.doraemon.api.common.enums.CommonResultCode;
import cn.net.yugu.doraemon.api.common.enums.IErrorCode;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.io.Serializable;
import java.util.Map;

/**
 * @description:
 * @author: wanghongli
 * @create: 2022-09-20 13:04:19
 */
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class BaseResult implements Serializable {
    private boolean success;
    private Integer code;
    private String message;
    private String requestId;
    private Map<String, Object> errorData;

    public BaseResult setErrorMessage(int code, String message) {
        this.code = code;
        this.success = false;
        this.message = message;
        return this;
    }

    public BaseResult setErrorMessage(IErrorCode code, Object... args) {
        this.code = code.getCode();
        this.success = false;
        this.message = String.format(code.getMessage(), args);
        return this;
    }

    public BaseResult setError(CommonResultCode rc, Object... args) {
        this.code = rc.code;
        this.success = false;
        if (args != null && args.length != 0) {
            this.message = String.format(rc.message, args);
        } else {
            this.message = rc.message;
        }
        return this;
    }

    public boolean isSuccess() {
        return code == CommonResultCode.SUCCESS.getCode();
    }

    public boolean isFail() {
        return !isSuccess();
    }
}
